
package com.sq.partner.manager.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.dao.TradSmsTemplateDao;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NlifePlan;
import com.sq.partner.manager.mybatis.model.TradInsuPlanGroup;
import com.sq.partner.manager.mybatis.model.TradPlanGroup;
import com.sq.partner.manager.mybatis.model.TradSmsTemplate;
import com.sq.partner.manager.service.IGatewayInsureService;
import com.sq.partner.manager.service.ITradInsuPlanGroupService;
import com.sq.partner.manager.service.ITradPlanGroupService;
import com.sq.partner.manager.util.FreeMarkerUtil;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * @author myl
 */
@Controller
@RequestMapping("/planGroupConfig")
public class PlanGroupConfigController {
	private static Logger logger = LogUtil.getLog(PlanGroupConfigController.class);
	@Resource
	private TradSmsTemplateDao tradSmsTemplateDao;
	@Resource
	IGatewayInsureService gatewayInsureService;
	@Resource
	ITradPlanGroupService tradPlanGroupService;
	@Resource
	ITradInsuPlanGroupService   iTradInsuPlanGroupService;	
	@Resource
	ITradInsuPlanGroupService tradInsuPlanGroupService;
	/**
	 * 跳转方案列表页面
	 */
	@RequestMapping(value = "/list")
	public String list(ModelMap model) throws Exception { 
		//初始化承保短信模板
		List<TradSmsTemplate> messageList = tradSmsTemplateDao.queryTrade(Constants.MESSAGETEMPLATE_TYPE);
		model.put("messageList", messageList);
		return "planGroupConfig/list";
	}
	/**
	 * 加载所有 投保单位
	 * @param size
	 * @param current
	 * @return
	 * @throws Exception
	 * loadChannelInfo
	 */
	@RequestMapping(value = "/loadChannelInfo")
	public @ResponseBody Page<GatewayChannelInfo> loadChannelInfo(HttpSession session,Integer size,Integer pageIndex,String channelCode,String channelName,String flag) throws Exception{
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelName(channelName);
		channelInfo.setChannelCode(channelCode);
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("flag", flag);
		page.setMap(map);
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		page.setType(channelInfo);
		Page<GatewayChannelInfo> p=gatewayInsureService.queryPageForGatewayChannelInfo(page);
		return p;
	}
	/***
	 * 组合方案组添加/修改
	 */
	@RequestMapping(value = "/saveGroup", method = RequestMethod.POST)
	@ResponseBody
	public Result saveGroup(HttpSession session,TradPlanGroup group,String flag) throws Exception {
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		String isCoreMessage = group.getIsCoreMessage();
		
		if(group==null){
			return Result.error("参数不可以为空");
		}
		if(StrUtil.isEmpty(group.getPartnerCode())){
			return Result.error("参数不可以为空");
		}
		if(StrUtil.isEmpty(group.getGroupCode())){
			return Result.error("组合方案组代码不能为空");
		}
		if(StrUtil.isEmpty(group.getGroupName())){
			return Result.error("组合方案组名称不能为空");
		}
		//编码
		String smsTemplet = URLDecoder.decode(group.getSmsTempletCode(), "UTF-8");
		group.setSmsTempletCode(smsTemplet);
		String mainTemplet = URLDecoder.decode(group.getMailTemplet(), "UTF-8");
		group.setMailTemplet(mainTemplet);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("groupCode", group.getGroupCode());
		/**查询id是否已经存在**/
		try {
			if("add".equals(flag)){
				List<TradPlanGroup>list= tradPlanGroupService.queryGroupByMap(map);
				if(list!=null&&list.size()>0){
					return Result.error("组合方案组代码已存在");
				}
				group.setIsProdGroup("0");	
				group.setOperTime(new Date());
				group.setOperUser(gatewayuser.getUserid());
				group.setGroupStatus("1");
				if(tradPlanGroupService.addTradPlanGroup(group)){
					return Result.success("添加成功");
				};
				return  Result.error("添加失败");	
			}else{
				tradPlanGroupService.editTradPlanGroup(group);
				return Result.success("修改成功");
			}
		
		} catch (Exception e) {
			logger.info(e);
			return Result.error("系统错误");
		}
	}
	/**
	 * 分页条件查询方案组
	 */
	@RequestMapping(value = "/queryGroupPageByCriteria")
	@ResponseBody
	public Page<Map<String,Object>> queryGroupPageByCriteria(HttpSession session,Page<Map<String,Object>> page,TradPlanGroup group,Integer pageIndex) throws Exception{
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		System.out.println(group.getGroupCode()==null);
		paramMap.put("groupCode", ("").equals(group.getGroupCode())?null:group.getGroupCode());
		paramMap.put("groupName", ("").equals(group.getGroupName())?null:group.getGroupName());
		page.setMap(paramMap);
		page=tradPlanGroupService.queryGroupByPage(page);
		return page;
	}
	/**
	 * 分页条件查询方案
	 */
	@RequestMapping(value = "/queryPlanPageByCriteria")
	@ResponseBody
	public Page<Map<String,Object>> queryPlanPageByCriteria(HttpSession session,Page<Map<String,Object>> page,String id ,String planCode,String planName,String isSeeMoney,String partnerCode) throws Exception{
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("planCode", ("").equals(planCode)?null:planCode);
		paramMap.put("planName", ("").equals(planName)?null:planName);
		paramMap.put("id", id);
		paramMap.put("isSeeMoney", ("").equals(isSeeMoney)?null:isSeeMoney);
		paramMap.put("partnerCode", partnerCode);
		page.setMap(paramMap);
		page=tradPlanGroupService.queryGroupPlanByPage(page);
		return page;
	}
	
	/***
	 * 组合方案组方案关联添加保存
	 */
	@RequestMapping(value = "/saveGroupPlan", method = RequestMethod.POST)
	@ResponseBody
	public Result saveGroupPlan(HttpSession session,String planNo,String requered,String planGroupId) throws Exception {
		if(StrUtil.isEmpty(planGroupId)||StrUtil.isEmpty(planNo)){
			return Result.error("参数错误");
		}
		List<TradInsuPlanGroup> groups=new ArrayList<TradInsuPlanGroup>();
		try {
			String [] planNos=planNo.split(",");
			String [] requereds=requered.split(",");
			for (int i = 0; i < planNos.length; i++) {
				if(StrUtil.isEmpty(planNos[i])){
					continue;
				}
				TradInsuPlanGroup group = new TradInsuPlanGroup();	
				group.setInsuPlanNumber(planNos[i]);
				group.setPlanGroupId(planGroupId);
				group.setRequired(requereds[i]);
				groups.add(group);
			
			}
			/**删除原方案组方案关联*/
			iTradInsuPlanGroupService.deleteTradInsuPlanGroupByGroupId(Long.parseLong(planGroupId));
			iTradInsuPlanGroupService.addPlanGroupList(groups);
			return Result.success("添加成功");
		} catch (Exception e) {
			logger.info(e);
			return Result.error("系统错误");
		}
	}
	/***
	 * 删除方案组
	 */
	@RequestMapping(value = "/delTradGroup", method = RequestMethod.POST)
	@ResponseBody
	public Result delTradGroup(HttpSession session,String  groupId) throws Exception {
		if(StrUtil.isEmpty(groupId)){
			return Result.error("参数错误");
		}
		try {
			/**删除原方案组方案关联*/
			iTradInsuPlanGroupService.deleteTradInsuPlanGroupByGroupId(Long.parseLong(groupId));
			tradPlanGroupService.deleteTradPlanGroup(Long.parseLong(groupId));
			return Result.success("删除成功");
		} catch (Exception e) {
			logger.info(e);
			return Result.error("系统错误");
		}
	}
	
	@RequestMapping(value = "/dowloadPlan")
	public void dowloadPlan(String groupId,HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception {
		ServletOutputStream outPutStream=null;

		/**浏览器处理*/
	    final String userAgent = request.getHeader("USER-AGENT");
	    logger.info("使用的浏览器"+userAgent);
		 try{
			 String  fileName="组合险方案sql.txt";
			 if(userAgent.indexOf( "MSIE")!=-1){
				 /**ie浏览器*/
				 fileName=java.net.URLEncoder.encode(fileName,"UTF-8"); 
			 }else if(userAgent.indexOf( "Mozilla")!=-1){
				 /**火狐浏览器*/
				 fileName = new String(fileName.getBytes(), "ISO8859-1");
			 }else{
				 /**其他浏览器*/
				 fileName=java.net.URLEncoder.encode(fileName,"UTF-8"); 
			 }
			 String[] groupIds=forGroupIds(groupId);
			 System.out.println(groupIds);
			 Map<String, Object> map=queryGroupPlanData(groupIds);
			 /**查询产品信息*/
			 response.setContentType("text/plain"); 
			 response.setHeader("Content-disposition","attachment; filename="+fileName);  
	         outPutStream=response.getOutputStream(); 
	         String ss=FreeMarkerUtil.process("groupPlan.ftl", map);
	         outPutStream.write(ss.getBytes());  
	         outPutStream.flush();
		    }catch(IOException e){
		    	logger.info("创建文件出错",e);
		  }finally{
			  if(outPutStream!=null){
				  outPutStream.close();
			  }
		  }
	}
	/**方案导出数据处理
	 * @throws Exception **/
	private Map<String, Object> queryGroupPlanData(String[] groupIds) throws Exception{
		 Map<String, Object> map=new HashMap<String, Object>();
		 map.put("groupIds", groupIds);
		 List<String> planSqls=new ArrayList<String>();
		 List<String> groupSqls=new ArrayList<String>();
		 /**导出方案*/
		 List<Map<String, Object>> groupPlans= tradPlanGroupService.impGroupPlan(map);
		 for (Map<String, Object> map2 : groupPlans) {
			 String sql=getInsertSql(map2, "T_TRAD_PLAN_GROUP");
			 planSqls.add(sql);
		 }
		 /**导出方案组*/
		 List<Map<String, Object>> realGroupPlans = tradInsuPlanGroupService.impRealGroupPlan(map);
		 for (Map<String, Object> map2 : realGroupPlans) {
			 String sql=getInsertSql(map2, "T_TRAD_INSU_PLAN_GROUP");
			 groupSqls.add(sql);
		 }
		 map.put("plans",planSqls );
		 map.put("groups", groupSqls);
		return map;
	}
	/**循环map返回insert语句**/
	private String getInsertSql(Map<String, Object> map,String table){
		String sql="INSERT INTO " +table;
		String cloum=" (";
		String value=" (";
		if(map!=null){
			for (String key : map.keySet()) {
				if(key.equalsIgnoreCase("oper_time")||key.equalsIgnoreCase("INSERT_TIME")||key.equalsIgnoreCase("UPDATE_TIME")||key.equalsIgnoreCase("OPRATE_TIME")){
					cloum+=key+",";
					value+="SYSDATE,";
					continue;
				}
				cloum+=key+",";
				if(map.get(key)!=null){
					value+="'"+map.get(key)+"',";
				}else{
					value+=map.get(key)+",";
				}
				
			}
			cloum=cloum.substring(0,cloum.length()-1)+" )";
			value=value.substring(0,value.length()-1)+" )";
		}
		return sql+cloum+" VALUES "+value;
	}
	
	/**方案id处理*/
	private String[] forGroupIds(String groupId){
		if(StrUtil.isEmpty(groupId)){
			return null;
		}
		String[] strs=groupId.split(",");
		return strs;
	}
	
}

